package com.prp.gwt.server;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.prp.algorithm.UserValidation;
import com.prp.bo.RegisterAuthMailSender;
import com.prp.bo.User;
import com.prp.db.po.UserInformation;
import com.prp.gwt.client.ClientConstants;
import com.prp.gwt.client.ClientException;
import com.prp.gwt.client.user.UserBaseService;

public class GlobalServiceImpl extends RemoteServiceServlet implements
		UserBaseService {

	private static final long serialVersionUID = 5150778524887077067L;

	public void validateAuth(int identity) throws ClientException {
		Object id = getThreadLocalRequest().getSession().getAttribute(
				ClientConstants.ATTR_USER);
		if (null == id)
			throw new ClientException("登录超时", "请重新登录<br/>原因可能是您长时间没有操作");
		if (com.prp.bo.User.getUser((Integer) id).getIdentity() < identity)
			throw new ClientException("您没有权限!", "您没有此操作的权限<br/>如有疑问请向管理员咨询");
	}

	public void signOut() {
		if (getThreadLocalRequest().getSession(false) != null)
			getThreadLocalRequest().getSession(false).invalidate();
	}

	public Map<Integer, String> register(final com.prp.gwt.client.vo.User user,
			String password, final String host) throws ClientException {
		HashMap<Integer, String> result = new HashMap<Integer, String>();
		if (!UserValidation.validateEmail(user.getEmail()))
			result.put(ClientConstants.USER_EMAIL, "请输入合法的电子邮件帐户");
		else if (User.hasUser(user.getEmail()))
			result.put(ClientConstants.USER_EMAIL, "此帐户已经被注册");
		if (!UserValidation.validateUsername(user.getUsername()))
			result.put(ClientConstants.USER_NAME, "请检查用户名");
		if (password == null || password.equals(""))
			result.put(ClientConstants.USER_PASSWORD, "密码不能为空");
		if (result.isEmpty()) {
			User.createUser(user.getEmail(), user.getUsername(), password);
			User
					.modifyUserInfo(User.getUser(user.getEmail()).getUserId(),
							user);
			Runnable r = new Runnable() {
				@Override
				public void run() {
					RegisterAuthMailSender.sendRegisterConfirmMail(user
							.getEmail(), host);
				}
			};
			new Thread(r).start();
		}
		return result;
	}

	public boolean verify(int identity) {
		Object id = getThreadLocalRequest().getSession().getAttribute(
				ClientConstants.ATTR_USER);
		if (null == id)
			return false;
		if (com.prp.bo.User.getUser((Integer) id).getIdentity() < identity)
			return false;
		return true;
	}

	@Override
	public boolean verify() {
		return verify(ClientConstants.USER);
	}

	@Override
	public com.prp.gwt.client.vo.User updateUser(int id) {
		if(id == -1)
		id = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if (!User.hasUser(id))
			return null;
		UserInformation info = User.getUser(id);
		return User.parse(info);
	}

}
